/*
 * NativeQueryIDL - NativeQuery Interface Definition Language
 * Copyright (C) 2010  Grzegorz Bugaj
 * http://www.gregbugaj.com
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/
package com.gregbugaj.nativequeryidl;

import java.util.List;

import com.gregbugaj.nativequeryidl.converters.ClobConverter;
import com.gregbugaj.nativequeryidl.converters.Converter;
import com.gregbugaj.nativequeryidl.converters.ConverterRegistry;
import com.gregbugaj.nativequeryidl.ex.MetaclassException;

/**
 * 
 * @author gbugaj
 *
 */
public class NativeQueryIDL {
	private static final String META_CLASS_NAME = "Meta";

	/**
	 * Transform row of data into an semi type-safe entity 
	 * @param <T>
	 * @param clazz to use as target to construct object from, it should have Meta definiton class
	 * @param row of data to transform 
	 * @return new transformed object of type T
	 * @throws Exception if there have been problem transforming the data
	 */
	public static <T> T transform(Class<T> clazz, Object[] row) throws MetaclassException, Exception {
		if(row == null)return null;
		T object=null;
		try {
			object=clazz.newInstance();
		} catch (Exception e) {
			e.printStackTrace();
		}
		Class<?> meta = NativeQueryIDL.getMetaClass(clazz);
		List<MetaDefinition> definitions = ReflectUtil.getMetaDefinitions(meta);
		ClobConverter clobConverter=new ClobConverter();
		for(MetaDefinition def:definitions){
			Object data=row[def.getDataIndex()];
			//FIXME:Generalize this so we have 2 types of converters from and to
			if(clobConverter.canConvert(data.getClass())){
				data=clobConverter.convert(data);
			}
			ReflectUtil.set(def.getPropertyField(), object, def.getConverter().convert(data));
		}
		return object;	
	}

	/**
	 * Class to introspect for possible MetaClass Definition
	 * @param clazz to introspect
	 * @return Meta class
	 * @throws MetaclassException
	 */
	public static Class<?> getMetaClass(Class<?> clazz) throws MetaclassException{		
		Class<?>[] decClasses = clazz.getDeclaredClasses();
		for(Class<?> c:decClasses){
			if(c.getSimpleName().equals(META_CLASS_NAME)){
				return c;
			}			
		}		
		throw new MetaclassException("Meta class not found in class "+clazz.getCanonicalName());
	}
}
